package com.yookey.common.Interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.yookey.common.context.AccountUtils;
import com.yookey.common.utils.JWTUtil;
import com.yookey.model.dto.AccountDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Date:Create：in 2019/11/20 14:33
 * @Modified By：
 */
@Component
public class RequestInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RequestInterceptor.class);

    @Value("${auth.skipUrls}")
    private String skipUrls;    //跳过验证的url列表

    private List<String> urls = null;

    private List<String> getUrls() {
        if (urls == null) {
            if (StringUtils.isBlank(skipUrls)) {
                urls = new ArrayList<String>();
            } else {
                urls = Arrays.asList(StringUtils.split(skipUrls, ','));
            }
            logger.info("init skip urls");
        }
        return urls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果关闭了验证则直接跳过
        //跳过不需要验证的路径
//        String url = request.getPathInfo();
        String url = request.getRequestURI();
        System.out.println("uri.path=" + url);
        List<String> urlList = getUrls();
        if (urlList.contains(url)) {
            return true;
        }
        String token = request.getHeader("token");
        //验证token
        if (StringUtils.isBlank(token) || JWTUtil.isBlackToken(token)) {
            sendError("401", "您没有权限访问，请先登录", response);
            return false;
        }
//        String tken = JWTUtil.verifyTokenRenewal(token, getJwtId(token));
        String tken = JWTUtil.verifyToken(token);
        if (tken == null || tken.isEmpty()) {
            sendError("401", "认证失败，请重新登录", response);
            return false;
        }
        Map<String, Claim> claimMap = JWTUtil.getClaims(token);
        AccountDTO accountDTO = JSON.parseObject(claimMap.get("data").asString(), AccountDTO.class);
        AccountUtils.set(accountDTO);
        return true;
    }

    private void sendError(String code, String message, HttpServletResponse response) throws IOException {
        response.setStatus(200);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("message", message);
        response.getWriter().write(json.toString());
    }

    public String getJwtId(String token) {
        String id = null;
        try {
            id = JWT.decode(token).getId();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
//            sendError("401", "无效的token", response);
        }
        return id;
    }
}
